//
// Created by admin on 2024/12/4.
//

#include "BarrierCurveRender.h"
#include "CurveMesh.h"
#include "CurveMeshBuilder.h"
#include <cmath>
#include <QDebug>

#include <sstream>

BarrierCurveRender::BarrierCurveRender() {
    initResources();
}

BarrierCurveRender::~BarrierCurveRender()
{

}

int BarrierCurveRender::getMiddleSampleSize()
{
    return m_samples.size();
}

Point BarrierCurveRender::getMiddleSample(int index)
{
    return m_samples.at(index);
}

Point BarrierCurveRender::getLeftSample(int index)
{
    return m_test_left_samples.at(index);
}

Point BarrierCurveRender::getRightSample(int index)
{
    return m_test_right_samples.at(index);
}

void BarrierCurveRender::initResources() {
    generateQuarterCircle(10, 200, &m_samples);

    CurveMeshBuilder mesh_builder;
    CurveMesh * ptr_mesh = mesh_builder.build(m_samples);
    m_test_left_samples = ptr_mesh->test_get_left_curve();
    m_test_right_samples = ptr_mesh->test_get_right_curve();

    ptr_vertex_buffer = ptr_mesh->generate_vertex_buffer();
    ptr_index_buffer = ptr_mesh->generate_index_buffer(ebo_size);


    int m_vertex_count = 30;
    float * vertices = new float[3*m_vertex_count];
    for(int i = 0; i < 3*m_vertex_count; i++){
        vertices[i] = ptr_vertex_buffer.get()[i];
    }

    std::stringstream ss_v;
    int v_index = 0;
    for(int i = 0; i < 3*m_vertex_count; i+= 3) {
        ss_v << "[" << v_index << "]:" << vertices[i]/200.0f << "," << vertices[i+1]/200.0f << "," << vertices[i+2] << " ";
        v_index++;

        if (v_index % 3 == 0) {
            ss_v << "\n";
        }

        if (v_index % 9 == 0 ) {
            ss_v << "\n";
        }
    }

    printf(ss_v.str().c_str());
    printf("\n\n");


    unsigned int * indices = new unsigned int [ebo_size];
    for(int i = 0; i < ebo_size; i++) {
        indices[i] = ptr_index_buffer.get()[i];
    }
    std::stringstream ss_e;
    for (int i = 0; i < ebo_size; i++) {
        ss_e << "[" << i << "] :" << indices[i] << ", ";

        if ( (i + 1) % 3 == 0) {
            ss_e << "\n";
        }
    }

    printf(ss_e.str().c_str());

    delete ptr_mesh;
}

/**
 * @brief 生成第一象限处的半圆形曲线的采样点
 * @param [in] sampleCount 采样点数量
 * @param [in] R 圆形半径
 * @param [out] samples 采样点数组
 */
void BarrierCurveRender::generateQuarterCircle(unsigned int sampleCount, unsigned int R, CurveSamples * samples) {
    if (samples == nullptr)
        return;

    samples->clear();

    std::vector<Point> sample_array;
    float ratio = 0.0f;
    float angle = 0.0f;
    float px, py;
    const float HALF_PI = M_PI / 2;
    for ( unsigned int i = 0; i < sampleCount; i++) {
        ratio = i / (float)sampleCount;
        angle = ratio * HALF_PI;
        px = R * cos(angle);
        py = R * sin(angle);

        Point p(px, py);
        sample_array.push_back(p);
    }

    samples->setSamples( sample_array);
}
